#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <cerrno>
#include "Comm.hpp"

void Usage(const std::string &proc)
{
    std::cout << "Usage:\n\t" << proc.c_str() << " server_ip server_port" << std::endl;
}

//./udp_client server_ip,server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
    }

    std::string serverip = argv[1];
    int16_t serverport = std::stoi(argv[2]);

    int socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketfd < 0)
    {
        std::cerr << "socket fail: " << strerror(errno) << std::endl;
        exit(Socket_Err);
    }
    std::cout << "create socket success," << socketfd << std::endl;

    sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);

    while (true)
    {
        std::string inbuffer;
        std::cout << "Please enter# ";
        getline(std::cin, inbuffer);
        int n = sendto(socketfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n > 0)
        {
            char buffer[1024];
            struct sockaddr_in tmp;
            socklen_t len = sizeof(tmp);
            int m = recvfrom(socketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&tmp, &len);
            if (m > 0)
            {
                buffer[n] = 0;
                std::cout << "server echo# " << buffer << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    close(socketfd);
    return 0;
}